<template>
  <div class="oe-ruleManage" v-loading="loading">
    <top-tip :showBack="false"></top-tip>
    <div class="oe-manage-search">
      <!-- <span class="oe-manage-text">规则名称：</span> -->
     
        <span class="oe-manage-input">
          <a-input placeholder="输入规则名称" v-model.trim="rule">
            <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
          </a-input>
          <a-button type="primary" @click.stop="searchList" class="chaxun">查询</a-button>
        </span>
        <span class="oe-manage-btns">
          <!-- <a-button type="primary" @click.stop="searchList">查询</a-button> -->
          <a-button type="primary" @click="onAddRule" v-if="operationList.includes('add/edit/del')">新增</a-button>
        </span>
      
    </div>
    <div class="oe-rule-content">
      <div class="oe-manage-contain">
        <a-table :columns="columns" :pagination="pagination" :dataSource="ruleList" @change="onTableChange">
          <span slot="Remarks" slot-scope="text" style="">
            <a-tooltip
              placement="bottom"
              :title="text"
              style="
                width: 240px;
                overflow: hidden; 
                text-overflow: ellipsis;
                white-space: nowrap;
                display: inline-block;
              "
            >
              <span>
                {{ text }}
                <!-- <router-link :to="{ name: 'ruleEdit', params: { examid: record.Id } }">{{ text }}</router-link> -->
              </span>
            </a-tooltip>
          </span>
          <span slot="action" slot-scope="record">
            <a-tooltip
              placement="bottom"
              title="编辑"
              v-if="record.IsCanEdit && !record.IsUsed && operationList.includes('add/edit/del')"
            >
              <span @click.stop="onEditRule(record)" class="action-icon">
                <i class="iconfont icon-edit"></i>
                <span>编辑</span>
              </span>
            </a-tooltip>
            <a-tooltip
              placement="bottom"
              title="查看"
              v-if="(!record.IsCanEdit || record.IsUsed) && operationList.includes('add/edit/del')"
            >
              <span @click.stop="onLookRule(record)" class="action-icon">
                <i class="iconfont icon-chakan"></i>
                <span>查看</span>
              </span>
            </a-tooltip>
            <a-tooltip
              placement="bottom"
              title="编辑成员"
              v-if="record.IsCanEdit && operationList.includes('add/edit/del')"
            >
              <span @click.stop="onEditRuleMember(record)" class="action-icon">
                <a-icon type="team" class="bianji"/>
                <span>编辑成员</span>
              </span>
            </a-tooltip>
            <a-tooltip
              placement="bottom"
              title="删除"
              v-if="record.IsCanEdit && operationList.includes('add/edit/del')"
            >
              <span @click.stop="onDelRule(record)" class="delete-icon action-icon">
                <i class="iconfont icon-delete"></i>
                <span>删除</span>
              </span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal title="编辑规则成员" class="oe-modal" :visible="memberVsible" @ok="handleOk" @cancel="handleCancels">
      <span class="oe-modal-text"> 成员教师：</span>
      <span class="oe-modal-input">
        <a-select
          mode="multiple"
          style="width: 100%"
          showSearch
          :allowClear="true"
          v-model="CreateName"
          optionFilterProp="children"
          @change="selectTeacher"
          placeholder="请输入教师的姓名或用户名查询"
        >
          <a-select-option v-for="item in selection" :index="index" :key="item.id">{{ item.text }} </a-select-option>
        </a-select>
      </span>
      <a-tooltip placement="bottomLeft">
        <template slot="title"> 不允许删除自己 </template>
        <span class="iconfont icon-wenti"></span>
      </a-tooltip>
      <template slot="footer">
        <a-button @click="addExamRuleMember()" type="primary" html-type="submit"> 确定 </a-button>
        <a-button @click.stop="handleCancels"> 取消 </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  name: 'rule-manage',
  mixins: [GetOperationList],
  components: {
    topTip,
  },
  data() {
    return {
      rule: '',
      selectedRowKeys: [],
      ruleList: [],
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0,
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'number',
          align: 'center',
          width: '8%',
        },
        {
          title: '名称',
          dataIndex: 'Title',
          align: 'center',
          sorter: true,
          width: '15%',
        },
        {
          title: '创建人',
          dataIndex: 'CreatorName',
          align: 'center',
          sorter: true,
          width: '10%',
        },
        {
          title: '创建时间',
          dataIndex: 'DateCreated',
          align: 'center',
          sorter: true,
          width: '15%',
        },
        {
          title: '规则总分',
          dataIndex: 'TotalScore',
          align: 'center',
          sorter: true,
          width: '10%',
        },
        {
          title: '备注',
          dataIndex: 'Remarks',
          key: 'Remarks',
          scopedSlots: { customRender: 'Remarks' },
          align: 'center',
          sorter: true,
          width: '8%',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          sorter: true,
          width: '28%',
        },
      ],
      addPrivilege: false, // 权限
      editPrivilege: false,
      delPrivilege: false,
      loading: false,
      ruleId: '', //规则Id
      memberVsible: false, //成员弹窗
      ruleMemberList: {},
      mainTeacherIds: [], //选择老师
      CreateName: [],
      operationList: [],
      userId: '',
    };
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  created() {
    this.getRuleMamageList();
    this.getOpeartion();
    this.getTeaList();
  },
  methods: {
    // 获取页面操作
    getOpeartion() {
      let that = this;
      this.loading = true;
      this.userId = window.localStorage.getItem('userId');
      this.operationList = [];
      this.GetOperationList().then((res) => {
        if (res.code == 1) {
          that.addPrivilege = true;
          that.editPrivilege = true;
          that.delPrivilege = true;

          if (res.list.length) {
            res.list.forEach((item) => {
              if (item.IsWrite) {
                this.operationList.push(item.Name);
              }
            });
          }
        }
      });
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getRuleMamageList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取列表
    getRuleMamageList(current, pageSize, sortOrder) {
      const urlApi = '/api/design/examrules/getExamRuleList';
      let prames = {
        ruleName: this.rule,
        papeType: false,
        sort: sortOrder || '',
        page: current || 1,
        pageSize: pageSize || 10,
      };
      let that = this;
      this.loading = true;
      this.$http.post(urlApi, prames).then((res) => {
        // console.log(res, 999);

        this.ruleList = [];
        if (res.code == 1) {
          this.pagination.current = res.pagination.pageIndex;
          this.pagination.pageSize = res.pagination.pageSize;
          this.pagination.total = res.pagination.totalCount;
          res.list.forEach((item, index) => {
            let number = (res.pagination.pageIndex - 1) * res.pagination.pageSize + index + 1;
            this.ruleList.push({
              ...item,
              number,
            });
          });
          // that.ruleList = res.list;
        }
        setTimeout(() => {
          this.loading = false;
        }, 2000);
      });
    },
    // 查询
    searchList() {
      this.getRuleMamageList();
    },
    // 新增
    onAddRule() {
      if (!this.addPrivilege) {
        return this.$message.info('当前用户没有权限');
      }
      this.$router.push({ name: 'ruleAdd' });
    },
    // 编辑
    onEditRule(record) {
      if (!this.editPrivilege) {
        return this.$message.info('当前用户没有权限');
      }
      this.$router.push({ name: 'ruleEdit', params: { examid: record.Id } });
    },
    // 查看
    onLookRule(record) {
      this.$router.push({ name: 'ruleLook', params: { examid: record.Id } });
    },
    // 编辑成员
    onEditRuleMember(record) {
      this.ruleId = record.Id;
      this.getExamRuleMemberList(record.Id);
      this.memberVsible = true;
    },
    //关闭弹窗
    handleCancels(e) {
      this.memberVsible = false;
      this.CreateName = [];
      this.mainTeacherIds = [];
    },
    //获取成员列表
    getExamRuleMemberList(id) {
      var that = this;
      this.$http
        .post('/api/design/ExamRules/getExamRuleMemberList', {
          ruleId: id,
        })
        .then((rst) => {
          if (rst.code > 0) {
            that.ruleMemberList = rst.list;
            that.CreateName = [];
            rst.list.forEach((item) => {
              let index = that.selection.findIndex((teacher) => {
                console.log(teacher.id, item.TeacherId);
                return teacher.id == item.TeacherId;
              });
              console.log(index);
              if (index > -1) {
                that.CreateName.push(that.selection[index].id);
                that.mainTeacherIds.push(that.selection[index].id);
              }
            });
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    //获取教师列表
    getTeaList() {
      this.$http
        .post('/api/design/course/getTeaList', {
          q: this.selected,
          courseId: '',
        })
        .then((res) => {
          this.selection = res;
        });
    },
    //编辑成员列表
    addExamRuleMember() {
      var that = this;
      this.$http
        .post('/api/design/ExamRules/addExamRuleMember', {
          ids: this.mainTeacherIds,
          ruleId: this.ruleId,
        })
        .then((rst) => {
          if (rst.code > 0) {
            that.$message.success(rst.msg);
            this.handleCancels();
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // //搜索多选
    selectTeacher(val) {
      this.mainTeacherIds = val;
    },

    // 删除
    onDelRule(record) {
      const urlApi = '/api/design/examrules/deleteRule';
      const params = { randomExamRuleId: record.Id };
      let that = this;
      if (!this.delPrivilege) {
        return this.$message.info('当前用户没有权限');
      }
      this.$confirm({
        title: '提示',
        content: '你确定要删除该规则吗？',
        centered: true,
        onOk: () => {
          this.loading = true;
          this.$http.post(urlApi, params).then((res) => {
            that.loading = false;
            if (res.code === 1) {
              that.$message.success(res.msg);
              that.getRuleMamageList();
            } else {
              that.$message.error(res.msg);
            }
          });
        },
      });
    },

    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
  },
};
</script>

<style></style>
